//
//  WBOAuchViewController.swift
//  czWB
//
//  Created by Qing on 2018/12/7.
//  Copyright © 2018年 成哥哥. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuchViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        title = "登录微博"

        view.backgroundColor = UIColor.white
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", target: self, action: #selector(stuff))
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        1.拼接url
        let urlString = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBAuthorize)")
        
//        2.发起请求
        guard let url = urlString else {
            
            return
        }
//        print("微博发起请求:\(url)")
        
        let request = URLRequest(url: url)
        
//        3.加载页面
        webView.loadRequest(request)
        
//        代理,用于监测微博发起请求时返回的结果Code
        webView.delegate = self
    }
    
    @objc private func stuff() {
        
//        准备好js格式
        let js = "document.getElementById('userId').value = 'zxcqing@sina.cn';" + "document.getElementById('passwd').value = 'sanrey.1204';"
        
//        让webView加载js,IOS仅且只有一个方法与javascrip交互的
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

    /// 登录返回页面
    @objc private func close() {
        
        dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}


extension WBOAuchViewController: UIWebViewDelegate {
    
    /// 监测webView将要加载请求时返回的结果
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型 点击链接加载\点击表单提交加载....
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        
        print("request加载--\(request)")
//        1.判断request是取消还是授权，如果是取消，request则包含 https://baidu.com/ 共有3种值：true/fasle/nil
//        print(request.url?.absoluteString.hasPrefix(WBAuthorize))
        
        if request.url?.absoluteString.hasPrefix(WBAuthorize) == false {
            
            return true
        }
        
//        2.如果是授权，request则包含https://baidu.com/? 共有3种值：true/fasle/nil
//        有包含则授权，否则取消授权，回到登录页面
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            SVProgressHUD.dismiss()
            return false
        }
        
//        3.提取code=后面的内容 https://baidu.com/?code=e2e09cd687542afa8b9c41e8be65562e
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
//                发空通知不违法。
                NotificationCenter.default.post(name: NSNotification.Name("WBUserloginSuccessNotifacaton"), object: nil)
//                1.关闭授权磁面
                self.close()
                
//                2.返回表格视图 --> 由MianViewController 接收通知完成
                
            }
        }
        
        return false
    }
    
    /// 网页请求开始加载时
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    /// 网页请求加载结束时
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
